/**
 * $Id: SMGPMessageConvertor.java,v 1.8 2006/09/15 01:59:57 martin Exp $
 *
 * Copyright 2005 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.messageconvertor.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.CommonMsgBean;
import com.haoxi.gateway.common.InitGatewayConfig;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.common.Text;
import com.haoxi.gateway.messageconvertor.MessageConvertor;
import com.haoxi.gateway.runner.smscommand.BaseCommandObj;
import com.haoxi.gateway.runner.smscommand.SubmitCmd;
import com.haoxi.gateway.runner.smscommand.SubmitReportCmd;
import com.haoxi.gateway.runner.smscommand.SubmitStatusCmd;
import com.haoxi.gateway.runner.smscommand.UserMOCmd;
import com.haoxi.gateway.smgpmsg.SMGP13DeliverMessage;
import com.haoxi.gateway.smgpmsg.SMGP13SubmitMessage;
import com.haoxi.gateway.smgpmsg.SMGP30DeliverMessage;
import com.haoxi.gateway.smgpmsg.SMGP30SubmitMessage;
import com.haoxi.gateway.smgpmsg.SMGPCommon;
import com.haoxi.gateway.smgpmsg.SMGPDeliverMessage;
import com.haoxi.gateway.smgpmsg.SMGPSubmitRespMessage;
import com.haoxi.gateway.smgpmsg.SMGPSequenceSower;

public class SMGPMessageConvertor extends MessageConvertor {
    private String protcolVersion;
    private static final Log log = LogFactory
            .getLog(SMGPMessageConvertor.class);
    private static final String SPLITREX = ",";

    public SMGPMessageConvertor(String gatewayCode) {
        super(gatewayCode);
        this.protcolVersion = InitGatewayConfig.getInstance().getGatewayInfo()
                .getProtocolVersion();

    }

    public CommonMsgBean convertCMDToCommonMsg(BaseCommandObj obj) {
        CommonMsgBean commonMsgBean = new CommonMsgBean();
        commonMsgBean.setGateWayCode(gatewayCode);
        try {
            if (obj instanceof SubmitCmd) {
                int subType = 0;
                SubmitCmd subCmd = (SubmitCmd) obj;
                // SMSP平台的收费方式0免费1点播2按条3包月4取消订阅5订阅请求
                // 这里的subtype需要加以区分
                // 此字段请参考SMSP平台中edit_fee.jsp页面sgmp1.3需要考虑此问题
                if (protcolVersion.equals(SYSConst.SMGP13)) {
                    int feeRecript = subCmd.getFeeRecript();
                    // 点播
                    if (1 == feeRecript) {
                        subType = 2;
                    }
                    // 订阅
                    else if (2 == feeRecript || 3 == feeRecript) {
                        subType = 3;
                    }
                    // 取消订阅
                    else if (5 == feeRecript) {
                        subType = 0;
                    }
                    // 订阅请求
                    else if (4 == feeRecript) {
                        subType = 1;
                    }
                }
                // 短消息子类型0 MO消息 6 MT消息
                int msgType = 6;
                // 是否要求返回状态报告（0=不要求，1=要求）
                int needReport = subCmd.getReg_del();
                // 发送优先级（从0到9）
                int priority = subCmd.getPriority();
                // 业务类型

                String serviceID = subCmd.getServiceId();
                // 收费类型（参见收费类型代码表）这里要做特殊处理
                // 00 免费 01 按条收费02 包月 03 封顶 其他 保留
                String feeType = subCmd.getFeeType();

                // 资费代码（单位为分）
                String feeCode = "000000";
                String fixedFee = "000000";
                // 按条或点播
                if ("01".equals(feeType)) {
                    feeCode = String.valueOf(subCmd.getFeeCode());
                }
                // 包月
                else if ("02".equals(feeType)) {
                    fixedFee = String.valueOf(subCmd.getFeeCode());
                }
                // 考虑版本兼容1.3中无fixedFee字段
                if (protcolVersion.equals(SYSConst.SMGP13)) {
                    feeCode = fixedFee;
                }
                if (feeCode.length() < 6) {
                    String tmp = "000000";
                    feeCode = tmp.substring(0, 6 - feeCode.length()) + feeCode;
                }
                if (fixedFee.length() < 6) {
                    String tmp = "000000";
                    fixedFee = tmp.substring(0, 6 - fixedFee.length())
                            + fixedFee;
                }
                // 短消息格式（参见短消息格式代码表）
                int msgCoding = subCmd.getMsgCoding();
                // 存活有效期，格式遵循SMPP3.3协议
                Date valid_time = null;
                // 定时发送时间，格式遵循SMPP3.3协议
                Date at_time = null;

                // 短消息发送用户号码
                String srcMobile = "118" + subCmd.getOrgMobile();
                // 计费用户号码
                String feeMobile = subCmd.getFeeMobile();
                // 短消息接收号码（连续存储DestTermIDCount个号码）
                String[] destTermId = subCmd.getDestMobile().split(SPLITREX);

                // 短消息内容
                String messageContent = subCmd.getMsgContent();
                // 保留
                String reserve = subCmd.getLinkID();
                // 考虑版本兼容submit消息有稍微区别
                if (protcolVersion.equals(SYSConst.SMGP30)) {
                    SMGP30SubmitMessage submitMsg = new SMGP30SubmitMessage(
                            msgType, needReport, priority, serviceID, feeType,
                            feeCode, fixedFee, msgCoding, valid_time, at_time,
                            srcMobile, feeMobile, destTermId, messageContent,
                            reserve);
                    SMGPSequenceSower.setTeleComSequence(submitMsg);
                    log.debug(submitMsg.toString());
                    subCmd.setSequence(String
                            .valueOf(submitMsg.getSequenceId()));
                    commonMsgBean.setBody(submitMsg.getBytes());
                } else if (protcolVersion.equals(SYSConst.SMGP13)) {
                    SMGP13SubmitMessage submitMsg = new SMGP13SubmitMessage(
                            subType, needReport, priority, serviceID, feeType,
                            feeCode, msgCoding, valid_time, at_time, srcMobile,
                            feeMobile, destTermId, messageContent, reserve);
                    SMGPSequenceSower.setTeleComSequence(submitMsg);
                    log.debug(submitMsg.toString());
                    subCmd.setSequence(String
                            .valueOf(submitMsg.getSequenceId()));
                    commonMsgBean.setBody(submitMsg.getBytes());
                }
                commonMsgBean.setReserve(subCmd);
            }
        } catch (Exception ex) {
            log
                    .error(
                            "Exception in SMGPMessageConvertor.convertCMDToCommonMsg(): Exception",
                            ex);
            commonMsgBean = null;
        }
        return commonMsgBean;
    }

    public BaseCommandObj convertCommonMsgToCMD(CommonMsgBean commonMsgBean) {
        int commid = commonMsgBean.getCommid();
        byte[] bodybytes = commonMsgBean.getBody();
        Object reserve = commonMsgBean.getReserve();
        if (SMGPCommon.SMGP_DELIVER == commid) {
            SMGPDeliverMessage deliver = null;
            if (protcolVersion.equals(SYSConst.SMGP30)) {
                deliver = new SMGP30DeliverMessage(bodybytes);
            } else if (protcolVersion.equals(SYSConst.SMGP13)) {
                deliver = new SMGP13DeliverMessage(bodybytes);
            }
            int isReport = deliver.getIsReport();
            if (0 == isReport) {
                UserMOCmd mocmd = new UserMOCmd();
                mocmd.setCommandID(commid);
                mocmd.setCommandLength(bodybytes.length + 8);
                mocmd.setConnName(commonMsgBean.getConnName());
                mocmd.setDestMobile(deliver.getDestTermID());
                mocmd.setGateWayCode(commonMsgBean.getGateWayCode());
                mocmd.setLinkId(deliver.getReserve());
                int msgFmt = deliver.getMsgFormat();
                mocmd.setMsgCoding(msgFmt);
                String msgContent = Text.getText(msgFmt, deliver
                        .getMsgContent());
                mocmd.setMsgContent(msgContent);
                mocmd.setMsgId(deliver.getMsgIdStr());
                mocmd.setOrgMobile(deliver.getSrcTermID());
                mocmd.setReserved(reserve);
                mocmd.setSequence(String.valueOf(deliver.getSequenceId()));
                mocmd.setSpNumber(deliver.getDestTermID());
                return mocmd;
            } else if (1 == isReport) {
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                SubmitReportCmd report = new SubmitReportCmd();
                report.setCommandID(commid);
                report.setCommandLength(bodybytes.length + 8);
                report.setConnName(commonMsgBean.getConnName());
                report.setDoneTime(format.format(deliver.getDoneTime()));
                report.setGatewayCode(commonMsgBean.getGateWayCode());
                report.setMsgID(deliver.getStatusMsgIdStr());
                report.setReport(deliver.getErr());
                report.setSequence(deliver.getMsgIdStr());
                report.setUserNumber(deliver.getSrcTermID());
                report.setUserNumberType(0);
                report.setReserved(reserve);
                return report;
            }
        } else if (SMGPCommon.SMGP_SUBMIT_RESP == commid) {
            SMGPSubmitRespMessage submitresp = new SMGPSubmitRespMessage(
                    bodybytes);
            SubmitStatusCmd submitCmd = new SubmitStatusCmd();
            submitCmd.setCommandID(commid);
            submitCmd.setCommandLength(bodybytes.length + 8);
            submitCmd.setMsgID(SMGPSequenceSower.getTeleComMsgId(submitresp.getMsgId()));
            submitCmd.setReserved(reserve);
            submitCmd.setSequence(String.valueOf(submitresp.getSequenceId()));
            submitCmd.setStatus(String.valueOf(submitresp.getStatus()));
            return submitCmd;
        }
        return null;
    }

    public String getProtcolVersion() {
        return protcolVersion;
    }
}
